package cc.yaomm.service.basic.manager;

import cc.yaomm.common.basic.util.BeanUtils;
import cc.yaomm.service.basic.entity.user.Permissions;
import cc.yaomm.service.basic.service.user.bo.PermissionResultBO;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class PermissionManager {

    /**
     * list转tree结构
     *
     * @param permissionsList
     * @return
     */
    public List<PermissionResultBO> convertTree(List<Permissions> permissionsList) {
        if (CollectionUtils.isEmpty(permissionsList)) {
            return new ArrayList<>();
        }

        //转map
        Map<String, PermissionResultBO> permissionMap = permissionsList.stream()
                .map(x -> BeanUtils.map(x, PermissionResultBO.class))
                .collect(Collectors.toMap(PermissionResultBO::getCode, x -> x, (v1, v2) -> v2, LinkedHashMap::new));

        //构造路由层级
        List<PermissionResultBO> permissionList = new ArrayList<>(permissionMap.size());
        permissionMap.forEach((code, value) -> {
            int pos = code.lastIndexOf(":");
            if (pos != -1) {
                String parentCode = code.substring(0, pos);
                PermissionResultBO resultBO = permissionMap.get(parentCode);
                if (Objects.nonNull(resultBO)) {
                    List<PermissionResultBO> children = resultBO.getChildren();
                    if (CollectionUtils.isEmpty(children)) {
                        children = Lists.newArrayList(value);
                        resultBO.setChildren(children);
                    } else {
                        children.add(value);
                    }
                } else {
                    log.warn("登录构建菜单时没有找到父级菜单，code:[{}]", code);
                }
            } else {
                permissionList.add(value);
            }
        });

        return permissionList;
    }

}
